package com.smartao.base.config;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.HashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.smartao.base.setting.Setting;
import com.smartao.base.setting.SettingService;
import com.smartao.core.config.BaseConfig;
import com.smartao.core.config.ConfigHolder;

@Service
public class ConfigService {
	
	protected final Logger logger = LoggerFactory.getLogger(getClass());
	
	@Autowired
	private SettingService settingService;
	
	/**
	 * 保存Config的值
	 * @param config BaseConfig子类
	 * @throws Exception 
	 */
	public void saveConfig(BaseConfig config) throws Exception{
		Field[] fields = config.getClass().getDeclaredFields();
		for(Field field :fields){
			// 静态方法除掉；
			if(Modifier.isStatic(field.getModifiers())){
				continue;
			}
			String fieldName = field.getName();
			String fieldKey = config.getFieldKey(fieldName);
			PropertyDescriptor pd = new PropertyDescriptor(fieldName ,config.getClass());
			Method getMethod = pd.getReadMethod();//获得get方法
			if(getMethod==null){
				continue;
			}
			Object value = getMethod.invoke(config);
			String fieldValue = value == null ? null : value.toString();

			Setting setting = settingService.findByKey(fieldKey);
			if(setting==null){
				continue;
			}
			setting.setSettingValue(fieldValue);
			settingService.save(setting);
			
			updateProperty(fieldKey,fieldValue);
		}
	}
	
	/**
	 * 更新ConfigHolder中保存的设置项
	 * @param key
	 * @param value
	 */
	private void updateProperty(String key, String value) {
		logger.debug("update config key:"+key+"  value:"+value);
		HashMap<String,String> properties = ConfigHolder.getInstance().getProperties();
		properties.put(key, value);
	}
	
}
